package com.meteor.service.impl;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.meteor.api.feign.system.SystemFeign;
import com.meteor.api.feign.system.dto.SysMerchantDTO;
import com.meteor.convert.OwnerRoomConvert;
import com.meteor.convert.VisitorConvert;
import com.meteor.entity.OwnerRoom;
import com.meteor.entity.Visitor;
import com.meteor.framework.common.base.ResponseData;
import com.meteor.framework.common.constant.Constant;
import com.meteor.framework.common.enums.UserAdminEnum;
import com.meteor.framework.common.exception.ServerException;
import com.meteor.framework.common.utils.PageResult;
import com.meteor.framework.mybatis.service.impl.BaseServiceImpl;
import com.meteor.framework.security.user.SecurityUser;
import com.meteor.mapper.OwnerRoomMapper;
import com.meteor.mapper.VisitorMapper;
import com.meteor.query.OrgAndCommunityQuery;
import com.meteor.query.OwnerRoomQuery;
import com.meteor.query.VisitorQuery;
import com.meteor.service.CommunityService;
import com.meteor.service.OwnerRoomService;
import com.meteor.service.VisitorService;
import com.meteor.vo.CommunityVO;
import com.meteor.vo.OwnerRoomListVO;
import com.meteor.vo.OwnerRoomVO;
import com.meteor.vo.VisitorVO;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @author lynn
 * @date 2024/1/22
 */


@Service
@AllArgsConstructor
public class OwnerRoomServiceImpl extends BaseServiceImpl<OwnerRoomMapper, OwnerRoom> implements OwnerRoomService {


    private final SystemFeign systemFeign;

    private final CommunityService communityService;


    @Override
    public void save(OwnerRoomVO vo) {
        OwnerRoom  entity= OwnerRoomConvert.INSTANCE.convert(vo);

        if(ObjectUtils.isEmpty(vo.getOwnerId())){
            entity.setOwnerId(SecurityUser.getUser().getId());
        }

        LambdaQueryWrapper<OwnerRoom> queryWrapper = new LambdaQueryWrapper<OwnerRoom>();
        queryWrapper.eq(OwnerRoom::getRoomId, vo.getRoomId());
        queryWrapper.eq(OwnerRoom::getOwnerId, vo.getOwnerId());
        queryWrapper.eq(OwnerRoom::getDeleted, 0);
        if (!ObjectUtils.isEmpty(baseMapper.selectOne(queryWrapper))) {
            throw new ServerException("已绑定不能重复绑定");
        }

        if(ObjectUtils.isEmpty(vo.getRoomStatus())){
            entity.setRoomStatus(Constant.OWNER_ROOM_STATUS_AUDITING);
        }


        if(!SecurityUser.getUser().getUsername().equalsIgnoreCase(UserAdminEnum.ADMIN.getValue())){

            if(ObjectUtils.isEmpty(vo.getOrgId())){
                entity.setOrgId(SecurityUser.getUser().getOrgId());
            }
            /*if(ObjectUtils.isEmpty(vo.getCommunityId())){
                OrgAndCommunityQuery query = new OrgAndCommunityQuery();
                query.setOrgId(vo.getOrgId());
                List<CommunityVO> communityVOS = communityService.orgCommunity(query);
                if(ObjectUtils.isEmpty(communityVOS)){
                    throw new ServerException("该机构下没有小区");
                }
                entity.setCommunityId(communityVOS.get(0).getId());
            }*/
        }else{
            if(ObjectUtils.isEmpty(vo.getOrgId())) {
                throw new ServerException("请选择机构");
            }
            ResponseData responseData = JSON.parseObject(systemFeign.orgMerchant(vo.getOrgId()),ResponseData.class);
            if(!ObjectUtils.isEmpty(responseData.getData())){
                SysMerchantDTO sysMerchantDTO = JSON.parseObject(responseData.getData().toString(),SysMerchantDTO.class);
                entity.setMerchantId(sysMerchantDTO.getId());
            }
            entity.setOrgId(vo.getOrgId());
            /*if(ObjectUtils.isEmpty(vo.getMerchantId())) {
                throw new ServerException("请选择商户");
            }*/
        }
        if(vo.getOwnerType().equalsIgnoreCase("yz")) {
            LambdaQueryWrapper<OwnerRoom> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(OwnerRoom::getRoomId, vo.getRoomId());
            wrapper.eq(OwnerRoom::getOwnerType, vo.getOwnerType());
            OwnerRoom ownerRoom = getOne(wrapper);
            if (!ObjectUtils.isEmpty(ownerRoom)) {
                throw new ServerException("该房间已存在业主");
            }
        }

//        entity.setMerchantId(SecurityUser.getUser().getMerchantId());
//        entity.setOrgId(SecurityUser.getUser().getOrgId());

        baseMapper.insert(entity);
    }

    @Override
    public void update(OwnerRoomVO vo) {
        OwnerRoom ownerRoom = OwnerRoomConvert.INSTANCE.convert(vo);
        if (ObjectUtils.isEmpty(ownerRoom.getId())) {
            throw new ServerException("修改失败，id为空");
        }
        baseMapper.updateById(ownerRoom);

    }

    @Override
    public OwnerRoomVO get(String id) {
        return OwnerRoomConvert.INSTANCE.convert(baseMapper.selectById(id));
    }

    @Override
    public List<OwnerRoomVO> getList(OwnerRoomQuery query) {

        LambdaQueryWrapper<OwnerRoom> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(StrUtil.isNotBlank(query.getCommunityId()), OwnerRoom::getCommunityId, query.getCommunityId());
        wrapper.eq(StrUtil.isNotBlank(query.getOwnerId()), OwnerRoom::getOwnerId, query.getOwnerId());
        wrapper.eq(query.getRoomStatus()!=null, OwnerRoom::getRoomStatus, query.getRoomStatus());

        List<OwnerRoom> complaints = baseMapper.selectList(wrapper);

        return OwnerRoomConvert.INSTANCE.convertList(complaints);
    }

    @Override
    public PageResult<OwnerRoomVO> page(OwnerRoomQuery query) {

        // 查询参数
        Map<String, Object> params = getParams(query);

        // 分页查询
        IPage<OwnerRoom> page = getPage(query);
        params.put(Constant.PAGE, page);

        // 数据列表
        List<OwnerRoomVO> list = baseMapper.getList(params);

        return new PageResult<>(list, page.getTotal());

//        IPage<Complaint> page = baseMapper.selectPage(getPage(query), getWrapper(query));
//
//        return new PageResult<ComplaintVO>(ComplaintConvert.INSTANCE.convertList(page.getRecords()), page.getTotal());
    }

    @Override
    public void delete(String id) {
        removeById(id);
    }

    @Override
    public List<OwnerRoomVO> getUserId(String userId) {
        List<OwnerRoomVO> list = new ArrayList<>();
        list = baseMapper.getUserId(userId,SecurityUser.getUser().getCommunityId(),1);
        if(!ObjectUtils.isEmpty(list)){

            List<OwnerRoomVO> ownerRoomVOS = baseMapper.getOwnerRoom(list.stream().map(t->t.getRoomId()).collect(Collectors.toList()));

            if(!ObjectUtils.isEmpty(ownerRoomVOS)) {
                Map<String, List<OwnerRoomVO>> ownerRoomMap = ownerRoomVOS.stream().collect(Collectors.groupingBy(t->t.getRoomId()));

                list.stream().forEach(t->{
                    if (t.getOwnerType().equalsIgnoreCase("yz")) {
                        //当前用户是该房间的业主
                        t.setCanUnBind(true);
                    } else {
                        //只能解绑自己
                        if(!ObjectUtils.isEmpty(ownerRoomMap.get(t.getRoomId()))) {
                            ownerRoomMap.get(t.getRoomId()).stream().filter(member -> member.getOwnerId().equals(t.getOwnerId()))
                                    .findFirst().get().setCanUnBind(true);
                        }
                    }
                    if(!ObjectUtils.isEmpty(ownerRoomMap.get(t.getRoomId()))) {
                        t.setMembers(ownerRoomMap.get(t.getRoomId()));
                    }
                });
//                ownerRoomVO.setMembers(ownerRoomVOS.stream().filter(t-> !t.getOwnerId().equals(userId)).collect(Collectors.toList()));
            }
        }
        return list;
    }

    @Override
    public OwnerRoomListVO getBindUserId(String userId) {

        OwnerRoomListVO ownerRoomListVO = new OwnerRoomListVO();
        List<OwnerRoomVO> list = new ArrayList<>();
        list = baseMapper.getUserId(userId,SecurityUser.getUser().getCommunityId(),null);

        List<OwnerRoomVO> applyList = list.stream().filter(t-> t.getRoomStatus().equals(0)).collect(Collectors.toList());
        List<OwnerRoomVO> bindList = list.stream().filter(t-> t.getRoomStatus().equals(1)).collect(Collectors.toList());
        List<OwnerRoomVO> rejectList = list.stream().filter(t-> t.getRoomStatus().equals(2)).collect(Collectors.toList());
        ownerRoomListVO.setApplyList(applyList);
        ownerRoomListVO.setBindList(bindList);
        ownerRoomListVO.setRejectList(rejectList);
        return ownerRoomListVO;
    }

    @Override
    public List<OwnerRoomVO> getAwaitUserId(String userId) {
        List<OwnerRoomVO> list = new ArrayList<>();
        list = baseMapper.getAwaitUserId(userId,SecurityUser.getUser().getCommunityId());
        List<OwnerRoomVO> ownerRoomVOS = new ArrayList<>();
        if(!ObjectUtils.isEmpty(list)){
            List<String> roomIds = list.stream().map(t->t.getRoomId()).collect(Collectors.toList());
            ownerRoomVOS = baseMapper.getOwnerRoomIds(roomIds);
        }
        return ownerRoomVOS;
    }

    @Override
    public void audit(OwnerRoomVO vo) {
        if(ObjectUtils.isEmpty(vo.getId())){
            throw new ServerException("审核失败，id为空");
        }
        OwnerRoom entity = getById(vo.getId());
        entity.setRoomStatus(vo.getRoomStatus());
        entity.setAuditTime(new Date());
        entity.setAuditOpinion(vo.getAuditOpinion());
        baseMapper.updateById(entity);
    }

    @Override
    public Integer getAwaitCountUserId(String userId) {
        return getAwaitUserId(userId).size();
    }

    @Override
    public void relieve(String id) {
        if(ObjectUtils.isEmpty(get(id))){
            throw new ServerException("解绑失败，绑定信息不存在");
        }
        removeById(id);
    }

    private Map<String, Object> getParams(OwnerRoomQuery query) {
        Map<String, Object> params = new HashMap<>();
        params.put("roomStatus", query.getRoomStatus());
        params.put("ownerId", query.getOwnerId());
        params.put("communityId", query.getCommunityId());

        // 数据权限
        params.put(Constant.DATA_SCOPE, getDataScope("t1", null,"pf_owner_room"));

        return params;
    }

    private Wrapper<OwnerRoom> getWrapper(OwnerRoomQuery query){
        LambdaQueryWrapper<OwnerRoom> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(query.getRoomStatus()!=null, OwnerRoom::getRoomStatus, query.getRoomStatus());
        wrapper.eq(StrUtil.isNotBlank(query.getOwnerId()), OwnerRoom::getOwnerId, query.getOwnerId());
        wrapper.eq(StrUtil.isNotBlank(query.getCommunityId()), OwnerRoom::getCommunityId, query.getCommunityId());

        // 数据权限
        dataScopeWrapper(wrapper);

        return wrapper;
    }
}
